// 权限控制相关
import router from "./router";
import store from "./store";
import systemApi from "@/views/systemSetting/systemSetting";

import NProgress from "nprogress";
import "nprogress/nprogress.css";
import {filterAsyncRouter} from "@/utils/createRoutes";
import {ElMessage} from "element-plus";
import {getURLhandler} from "@/common/utils/GlobalUtils";
import loginApi from "@/api/login";

const whiteList = ["/login", "/404"];
// const isAdmin = store.state.user.isAdmin || localStorage.getItem('isAdmin')

// 全局进度条的配置
NProgress.configure({
  easing: "ease", // 动画方式
  speed: 1000, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 更改启动时使用的最小百分比
  parent: "body", //指定进度条的父容器
});

/**
 * 获取菜单权限
 */
const getRoutes = async (to,next) => {
  if (store.state.menu.leftMenu.length === 0) { // 有token 无菜单路由
    const res = await systemApi.role.getUserPermission();
    if (res.code === '200') {
      // 无菜单权限
      if (res.data.menus === null || (Array.isArray(res.data.menus) && res.data.menus.length === 0)) {
        ElMessage.warning('无菜单权限,请联系管理员!!!')
        store.commit('RESET_STATE');
        return next({path: '/login'});
      }

      let list = filterAsyncRouter(res.data.menus);
      store.commit('SetLeftMenu', list);
      list.forEach(route => {
        router.addRoute(route);
      });

      next(to.path);

    } else { // 有token 获取菜单失败
      next({path: '/login'});
      store.commit('RESET_STATE');
    }
  } else { // 有token 有菜单路由
    next();
  }
}

/**
 * 设置用户信息
 */
const setUserInfo = (data) => {
  const userId = data.userId;
  store.commit("SET_USERID", userId);
  const userName = data.userName;
  store.commit("SET_USERNAME", userName);
  const account = data.account;
  store.commit("SET_USERACCOUNT", account);
  const email = data.email;
  store.commit("SET_EMAIL", email);
  const phoneNumber = data.phoneNumber;
  store.commit("SET_PHNOE", phoneNumber);//departmentId
  const departmentName = data.departmentName;
  store.commit("SET_DEPARTMENT", departmentName);
  const departmentId = data.departmentId;
  store.commit("SET_DEPARTMENT_ID", departmentId);
}

/**
 * token是否存在
 */
const isExistToken = (to) => {
  if(to?.query?.token){
    return  true;
  }
  if(getURLhandler(to.path).token){
    return  true;
  }
  return false;
}

/**
 * 获取链接中的token
 */
const getLinkToken = (to) => {
  if(to?.query?.token){
    return  to?.query?.token;
  }
  if(getURLhandler(to.path).token){
    return getURLhandler(to.path).token;
  }
  return '';
}

const setTokenFun =async (to,next) => {
  await store.commit("SET_TOKEN", {
    access_token: getLinkToken(to),
    refresh_token: getLinkToken(to)
  });
  const res = await  loginApi.getInfo();
  if(res.code==='200'){
    setUserInfo(res.data);
  }
  await getRoutes(to, next);
}

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  if(to.path==='/'){ // 系统没有设置无根路由,遇到'/'直接跳登录
    store.commit('RESET_STATE');
    return next({path:'/login'});
  }

  if (whiteList.indexOf(to.path) !== -1) { // 白名单 在免登录白名单，直接进入
    next();
  } else {
    if (!store.state.user.refreshToken) { // 无token
      if(isExistToken(to)){
        await setTokenFun(to, next);
      }else{
        next({path:'/login'});
        store.commit('RESET_STATE');
      }
    }else{ // 有token
      if(isExistToken(to)){
        await store.commit("SET_TOKEN", {
          access_token: getLinkToken(to),
          refresh_token: getLinkToken(to)
        });
        const res = await  loginApi.getInfo();
        if(res.code==='200'){
          setUserInfo(res.data);
        }
      }
      await getRoutes(to, next);
    }
  }

  if(to.path!=='/login'){
    // 遇到文档预览"路由"跳过,不记录进标签页
    let pathList = ['/document/docx','/document/pdf'];
    if(!pathList.includes(to.path) && to.name!=='404'){
      let menuObj = {
        path: to.path,
        name: to.name,
        title: to.meta.title,
      };
      store.commit("SET_BREAD_ITEMS", menuObj);
    }
  }

});

router.afterEach(() => {
  NProgress.done();
});
